package capitulo6;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class SpriteTest extends JFrame implements Runnable{
	int screenWidth = 640;
	int screenHeight = 480;
	
	// Double buffer objects
	BufferedImage backBuffer;
	Graphics2D g2d;
	
	Sprite asteroid;
	Sprite asteroid2;
	Sprite asteroid3;
	ImageEntity backGround;
	Thread gameLoop;
	Random rand = new Random();
	
	public static void main(String[] args) {
		new SpriteTest();
	}

	public SpriteTest(){
		super("Sprite Test");
		setSize(screenWidth,screenHeight);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		backBuffer = new BufferedImage(screenWidth,screenHeight,BufferedImage.TYPE_INT_RGB);
		g2d = backBuffer.createGraphics();
		
		// Load the background
		backGround = new ImageEntity(this);
		backGround.load("bluespace.png");
		
		// Load the sprite
		asteroid = new Sprite(this, g2d);
		asteroid.load("asteroid2.png");
		//int width = screenWidth - asteroid.imageWidth() -1;
		//int height = screenHeight - asteroid.imageHeight() -1;
		Point point = new Point(0, 80);
		asteroid.setPosition(point);
		Point Vel = new Point(1,0);
		asteroid.setVelocity(Vel);
		
		asteroid2 = new Sprite(this, g2d);
		asteroid2.load("asteroid2.png");
		Point point2 = new Point(600,80);
		asteroid2.setPosition(point2);
		Point Vel2 = new Point(-1,0);
		asteroid2.setVelocity(Vel2);
		
		gameLoop = new Thread(this);
		gameLoop.start();
	}
	
		
	@Override
	public void run() {
		Thread t = Thread.currentThread();
		while (t == gameLoop){
			try {
				Thread.sleep(30);
			} catch (Exception e) { e.printStackTrace(); }
			
			// draw the background
			g2d.drawImage(backGround.getImage(), 0,0, screenWidth -1, screenHeight -1, this);
	
			asteroid.updatePosition();
			asteroid2.updatePosition();
			asteroid.transform();
			asteroid2.transform();

			if (asteroid.collidesWith(asteroid2)) {
				asteroid.setVelocity(changeOrientation(asteroid.velocity()));	
				asteroid2.setVelocity(changeOrientation(asteroid2.velocity()));	
			} 
				
			asteroid.draw();
			asteroid.drawBounds(Color.GREEN);
			asteroid2.draw();
			asteroid2.drawBounds(Color.GREEN);
			repaint();
		}
	}
	
	public void paint(Graphics g){
		// draw the back buffer to the screen
		g.drawImage(backBuffer, 0,0, this);
	}

	public Point changeOrientation(Point p) {
		Point ptemp = new Point();
		if (p.x !=0) ptemp.x = -p.x;
		if (p.y !=0) ptemp.y = -p.y;
		return ptemp;
	}
}
